import type { CardList, CardQueryParams, SearchConfigDealItem } from '/@/api/general/model/cardModel';
import type { DeckInfoCardItem } from '/@/api/currentDeck/model/deckModel';
import { SearchLogicTypeEnum } from '/@/api/currentDeck/model/deckModel';
import { computed, defineComponent, reactive, ref, toRaw, unref } from 'vue';
import { appShareUsing } from '/@/utils/appInteractive';
import { useRouter } from 'vue-router';
import { useGeneralGameHooks } from '/@/views/general/hooks/useConfigs';
import { useCurrentDeckStore } from '/@/store/modules/currentDeck';
import { useElementSize } from '@vueuse/core';
import { awaitWrap, filterNullAttributes, judgeSystem } from '/@/utils';
import { cloneDeep, find, debounce, includes } from 'lodash-es';
import Title from '/@/views/general/components/Title';
import { Button, ConfigProvider, Empty, Field, List } from 'vant';
import { Icon } from '/@/components/Icon';
import { CardListApi } from '/@/api/general/card';
import { DeckCardDetailApi } from '/@/api/currentDeck/deck';
import BaseSearchPopup from '/@/views/general/components/CardSearch/BaseSearchPopup';
import SeriesSearchPopup from '/@/views/general/components/CardSearch/SeriesSearchPopup';
import CurrentAttrPopup from '/@/views/general/components/CardSearch/CurrentAttrPopup';
import DeckCardDetailPopup from '/@/views/currentDeck/components/DeckCardDetailPopup';
import ChooseCardPopup from './components/ChooseCardPopup';
import SearchHistory from '/@/views/general/components/SearchHistory';

import('./index.less');

export default defineComponent({
  name: 'CurrentDeckCardPage',
  setup() {
    // 设置分享参数
    appShareUsing({} as any);

    const currentStore = useCurrentDeckStore();
    const router = useRouter();
    const leftClick = () => {
      router.back();
    };

    const { getGameConfig, getSearchConfig } = useGeneralGameHooks();
    getGameConfig({ game_id: currentStore.gameId });
    getSearchConfig({ game_id: currentStore.gameId });

    const queryState = reactive<CardQueryParams>({
      game_id: currentStore.gameId,
      page: 1,
      size: 18,
      name: '',
      series_ids: [],
    });

    // 数据获取
    const listLoading = ref(false); // 是否处于加载状态 默认不处于，流会去加载数据
    const listFinished = ref(false); // 是否全部数据加载完成
    const listEmpty = ref(false);
    const listData = reactive<CardList>({
      total_page: 0,
      rows: [],
    });

    const getList = async (isRefresh: boolean) => {
      if (isRefresh) {
        queryState.page = 1;
        listData.rows = [];
        listData.total_page = 0;
        listLoading.value = true;
      }
      const params: CardQueryParams = filterNullAttributes(queryState, []);
      const [error, result] = await awaitWrap(CardListApi(toRaw(params), 'notify', true));
      if (error || !result) {
        return;
      }
      if (queryState.page === 1) {
        listFinished.value = false;
        !result.rows.length ? (listEmpty.value = true) : (listEmpty.value = false);
      }
      for (const item of result.rows) {
        listData.rows.push(item);
      }
      listLoading.value = false;
      if (result.total_page === queryState.page || !result.total_page) {
        listFinished.value = true;
        return;
      }
      queryState.page += 1;
    };

    // 详情
    const detailState = ref(false);
    const detailCardIdState = ref(0);
    const CardItem = ({ card }: { card: DeckInfoCardItem }) => {
      const CardAction = () => {
        const target = find(unref(allSelectCards), ['id', card.id]);
        target ? (card.number = target.number) : (card.number = 0);
        return (
          <ConfigProvider
            themeVars={{ buttonBorderWidth: 0 }}
            class={'card-action-buttons flex justify-between absolute bg-white'}
          >
            <Button
              plain
              icon={'minus'}
              size={'small'}
              type='primary'
              round
              disabled={!card.number}
              onClick={() => {
                delCardClick(card);
              }}
            />
            <span class={`card-nums ${card.number ? '' : 'hidden'}`}>x{card.number}</span>
            <Button
              plain
              icon={'plus'}
              size={'small'}
              type='primary'
              round
              onClick={() => {
                addCardClick(card);
              }}
            />
          </ConfigProvider>
        );
      };
      let AbbrPrice: VueNode = null;
      const { series_cn_abbr, price } = card;
      if (series_cn_abbr || price) {
        const Abbr = (
          <span class={'w-[50%] px-sm text-center van-ellipsis border-r border-gray-300'}>{series_cn_abbr || '-'}</span>
        );
        const Price = price ? (
          <span class={'flex-1 px-sm text-center van-ellipsis'}>¥{price / 100}</span>
        ) : (
          <span class={'flex-1 px-sm text-center van-ellipsis'}>¥-</span>
        );
        AbbrPrice = (
          <div class={'flex text-[16px] pb-sm text-gray-600'}>
            {Abbr}
            {Price}
          </div>
        );
      }
      return (
        <li class={'card-item'} onClick={() => {}}>
          <div class={'image'}>
            <img
              src={card.img}
              alt=''
              onClick={() => {
                detailState.value = true;
                detailCardIdState.value = card.id;
              }}
            />
          </div>
          <div class={'name-box'}>
            <div class={'name-content van-ellipsis text-xs px-md'}>{card.name}</div>
            {AbbrPrice}
          </div>
          <CardAction />
        </li>
      );
    };

    // 添加操作
    const selectCards = ref(cloneDeep(currentStore.getCreateDeckParams.deck_info));
    const allSelectCards = computed(() => {
      const allArray: DeckInfoCardItem[] = [];
      for (const item of unref(selectCards)) {
        allArray.push(...item.card_list);
      }
      return allArray;
    });
    const addCardClick = debounce(async (card: DeckInfoCardItem) => {
      let requestFlag = true;
      for (const deckCards of unref(selectCards)) {
        const target = find(deckCards.card_list, ['id', card.id]);
        if (!target) {
          continue;
        }
        target.number! += 1;
        deckCards.card_number += 1;
        requestFlag = false;
        break;
      }
      if (!requestFlag) {
        return;
      }

      // 如果不存在原来的数组中
      const [error, cardDetail] = await awaitWrap(DeckCardDetailApi(card.id));
      if (error || !cardDetail) {
        return;
      }
      for (const group of currentStore.getCardGroup) {
        const flag: boolean[] = [];
        group.conditions.map((cItem, index) => {
          flag.push(false);
          switch (cItem.condition) {
            case '=':
              if (cardDetail[cItem.attr_key] == cItem.value) {
                flag[index] = true;
              }
              break;
            case '<':
              if (cardDetail[cItem.attr_key] < cItem.value) {
                flag[index] = true;
              }
              break;
            case '>':
              if (cardDetail[cItem.attr_key] > cItem.value) {
                flag[index] = true;
              }
              break;
            case '<=':
              if (cardDetail[cItem.attr_key] <= cItem.value) {
                flag[index] = true;
              }
              break;
            case '>=':
              if (cardDetail[cItem.attr_key] >= cItem.value) {
                flag[index] = true;
              }
              break;
          }
        });
        if (
          (group.logic === SearchLogicTypeEnum.AND && !includes(flag, false)) ||
          (group.logic === SearchLogicTypeEnum.OR && includes(flag, true))
        ) {
          const deckCards = find(unref(selectCards), ['group_name', group.group_name]);
          if (!deckCards) {
            continue;
          }
          deckCards.card_list?.push({
            id: cardDetail.id,
            img: cardDetail.img,
            name: cardDetail.name,
            number: 1,
            series_abbr: cardDetail.series_abbr,
            price: cardDetail.price || 0,
          });
          deckCards.card_number += 1;
          break;
        }
      }
    }, 200);
    const delCardClick = (card: DeckInfoCardItem) => {
      for (const deckCards of unref(selectCards)) {
        const target = find(deckCards.card_list, ['id', card.id]);
        if (!target) {
          continue;
        }
        target.number! -= 1;
        deckCards.card_number -= 1;
        if (!target.number) {
          let delIndex = 0;
          deckCards.card_list.filter((item, index) => {
            if (item.id === target.id) {
              delIndex = index;
            }
          });
          deckCards.card_list.splice(delIndex, 1);
        }
      }
    };
    const confirmAddCards = () => {
      currentStore.setDeckInfo(unref(selectCards));
      router.back();
    };

    // region 适配安卓键盘
    const bottomSearchClass = ref('');
    const fieldFocusClick = () => {
      searchHistoryState.value = true;
      console.log(judgeSystem());
      if (judgeSystem() === 'android') {
        bottomSearchClass.value = 'android';
        return false;
      }
      bottomSearchClass.value = '';
    };
    const fieldBlurClick = () => {
      bottomSearchClass.value = '';
      setTimeout(() => {
        searchHistoryState.value = false;
      });
    };
    const searchFieldSlot = {
      button: () => {
        return (
          <Button
            type={'primary'}
            size={'small'}
            onClick={() => {
              getList(true);
            }}
          >
            搜索
          </Button>
        );
      },
    };
    // endregion

    // region 筛选Popup
    const searchState = ref(false);
    const seriesPopupState = ref(false);
    const currentPopupState = ref(false);
    const chooseShowState = ref(false);
    // 打开其他条件筛选
    const filterClick = () => {
      searchState.value = true;
    };
    // 打开系列筛选
    const seriesPopupClick = () => {
      seriesPopupState.value = true;
    };
    // 打开其他动态筛选浮层
    const currentAttrRef = ref<SearchConfigDealItem>({} as SearchConfigDealItem);
    const currentPopupClick = (currentAttr: SearchConfigDealItem) => {
      currentAttrRef.value = currentAttr;
      currentPopupState.value = true;
    };
    // endregion

    // 搜索记录
    const searchHistoryState = ref(false);
    const bottomAreaRef = ref();
    const { height } = useElementSize(bottomAreaRef);
    const setQueryName = (name: string) => {
      console.log(name);
      queryState.name = name;
      getList(true);
    };

    return () => (
      <div class='current-deck-card-page'>
        <Title title={'添加单卡'} leftArrow onLeftClick={leftClick} />
        <div class={'card-list-container'}>
          {unref(listEmpty) ? (
            <Empty>未找到相关卡牌</Empty>
          ) : (
            <List
              v-model={[listLoading.value, 'loading']}
              finished={unref(listFinished)}
              finishedText={'没有更多卡牌'}
              onLoad={getList}
              offset={0}
            >
              <ul class='card-list flex flex-wrap'>
                {listData.rows.map((card) => {
                  return <CardItem card={card} />;
                })}
              </ul>
            </List>
          )}
        </div>
        <div class={`bottom-area flex ${unref(bottomSearchClass)}`} ref={bottomAreaRef}>
          <SearchHistory
            gameId={currentStore.getGameId}
            queryParams={queryState}
            v-model={[searchHistoryState.value, 'show']}
            areaHeight={height.value}
            onSetQueryParamsName={setQueryName}
          />
          <div class={'bottom-search flex items-center'}>
            <div class={'input-box'}>
              <Field
                v-model={[queryState.name]}
                placeholder='卡牌名称或规则'
                leftIcon={'search'}
                v-slots={searchFieldSlot}
                clearable
                onFocus={fieldFocusClick}
                onBlur={fieldBlurClick}
              />
            </div>
            <div class='svg-button filter text-center' onClick={filterClick}>
              <Icon icon={'single-filter|svg'} size={30} />
              <span class={'block text-sm'}>筛选</span>
            </div>
          </div>
          <Button
            size={'large'}
            type={'primary'}
            class={'add-button'}
            disabled={!unref(allSelectCards).length}
            onClick={confirmAddCards}
          >
            确认添加
          </Button>
        </div>
        <div
          class={'choose-popup-button'}
          onClick={() => {
            chooseShowState.value = true;
          }}
        >
          查看已选
        </div>
        <BaseSearchPopup
          v-model={[searchState.value, 'show']}
          queryState={queryState}
          onPageRefresh={() => {
            getList(true);
          }}
          onOpenSeriesPopup={seriesPopupClick}
          onOpenCurrentAttrsPopup={currentPopupClick}
        />
        <SeriesSearchPopup
          v-model={[seriesPopupState.value, 'show']}
          queryState={queryState}
          gameId={currentStore.gameId}
          onPageRefresh={() => {
            getList(true);
          }}
        />
        <CurrentAttrPopup
          v-model={[currentPopupState.value, 'show']}
          queryState={queryState}
          currentAttrs={currentAttrRef}
          onPageRefresh={() => {
            getList(true);
          }}
        />
        <DeckCardDetailPopup v-model={[detailState.value, 'show']} cardId={detailCardIdState.value} />
        <ChooseCardPopup
          v-model={[chooseShowState.value, 'show']}
          deckCardList={unref(selectCards)}
          onAddCard={addCardClick}
          onDelCard={delCardClick}
        />
      </div>
    );
  },
});
